package de.fsujena.chat_pi.server.userInterface;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.util.Date;

import de.fsujena.chat_pi.ressources.User.ROLE;
import de.fsujena.chat_pi.ressources.message.TextMessage;
import de.fsujena.chat_pi.server.Server;

public class ConsoleUI implements UserInterface {
	DateFormat df;
	BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
	Server serverObject;

	public ConsoleUI(Server serverObject) {
		df = DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT );
		this.serverObject = serverObject;
	}

	@Override
	public void postTextMessage(TextMessage msg) {
		String temp="["+msg.getSenderUsername().toUpperCase()+" ("+df.format(msg.getReceived())+")]" + ">> " + msg.getMessageText();
		System.out.println(temp);
		serverObject.msgArray.add(temp);
		serverObject.saveHistory();
	}

	@Override
	public void postOwnTextMessage(String str) {
		// do not post own text messages
	}

	@Override
	public void postInfo(String str) {
		String temp="[INFO ("+df.format(new Date())+")]" + ">> " + str;
		System.out.println(temp);
		serverObject.msgArray.add(temp);
		serverObject.saveHistory();
	}

	@Override
	public void postWarning(String str) {
		String temp="[WARNING ("+df.format(new Date())+")]" + ">> " + str;
		System.out.println(temp);
		serverObject.msgArray.add(temp);
		serverObject.saveHistory();
	}

	@Override
	public void postError(String str) {
		String temp="[ERROR ("+df.format(new Date())+")]" + ">> " + str;
		System.err.println(temp);
		serverObject.msgArray.add(temp);
		serverObject.saveHistory();
	}
	public void postText(String str){
		System.out.println(str);
	}

	@Override
	public void run() {		
		while (true) {
			String cmd = null;
			try {
				cmd = input.readLine();		//read from console

			} catch (Exception e) {
				e.printStackTrace();

			}

			if (cmd.startsWith("$")) {		//checks if input is a command
				serverObject.commander(cmd);				//if yes, call commander
			} else if(serverObject.isStarted) {
				serverObject.networkListener.sendServerTextMessage(cmd);
				this.postOwnTextMessage(cmd);
			}
		}
	}
	
	
}
